﻿using System.Collections.Generic;

namespace Jayden.Dll.Core.Persistence.Queries
{
	public class Query
	{
		private List<QueryField> m_Fields = new List<QueryField>();
		private QueryFilter m_Filter = null;
		private List<QueryOrderField> m_Order = new List<QueryOrderField>();
		private List<QueryField> m_Groups = new List<QueryField>();

		public List<QueryField> Fields { get { return m_Fields; } }
		public QueryFilter Filter { get { return m_Filter; } set { m_Filter = value; } }
		public List<QueryField> Groups { get { return m_Groups; } }
		public List<QueryOrderField> Order { get { return m_Order; } }

		public override string ToString()
		{
			List<string> statements = new List<string>();
			List<string> fields = new List<string>();
			HashSet<string> tables = new HashSet<string>();
			foreach (QueryField field in m_Fields)
			{
				fields.Add(field.ToString());
				if(!string.IsNullOrWhiteSpace(field.TableName))
					tables.Add(field.TableName);
			}
			if (fields.Count == 0)
				fields.Add("*");
			statements.Add(string.Format("SELECT {0}", string.Join(", ", fields)));
			if (m_Filter != null)
				statements.Add(string.Format("WHERE {0}", m_Filter.ToString()));
			if (m_Groups.Count > 0)
			{
				List<string> groupBy = new List<string>();
				foreach (QueryField field in m_Groups)
				{
					groupBy.Add(field.QueryName);
					if (!string.IsNullOrWhiteSpace(field.TableName))
						tables.Add(field.TableName);
				}
				statements.Add(string.Format("GROUP BY {0}", string.Join(", ", groupBy)));
			}
			if (m_Order.Count > 0)
			{
				List<string> orderBy = new List<string>();
				foreach (QueryOrderField field in m_Order)
				{
					orderBy.Add(field.ToString());
					if (!string.IsNullOrWhiteSpace(field.TableName))
						tables.Add(field.TableName);
				}
				statements.Add(string.Format("ORDER BY {0}", string.Join(", ", orderBy)));
			}
			statements.Insert(1, string.Format("FROM {0}", string.Join(", ", tables)));
			return string.Join(" ", statements);
		}
	}
}
